/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.plan.score.ByProblemSearchDTO;
import org.springblade.modules.admin.entity.MaintainByScoreQuestionAppeal;
import org.springblade.modules.admin.entity.MaintainPlanContent;
import org.springblade.modules.admin.enums.ByScoreQuestionAppealEnum;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.ByScoreQuestionAppealService;
import org.springblade.modules.admin.service.IMaintainPlanContentService;
import org.springblade.modules.admin.vo.check.ProblemStatusVo;
import org.springblade.modules.admin.vo.plan.store.ByProblemResultVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.admin.entity.MaintainByScoreQuestion;
import org.springblade.modules.admin.vo.MaintainByScoreQuestionVO;
import org.springblade.modules.admin.wrapper.MaintainByScoreQuestionWrapper;
import org.springblade.modules.admin.service.IMaintainByScoreQuestionService;
import org.springblade.core.boot.ctrl.BladeController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 保养评分工作项评分问题 控制器
 *
 * @author ysq
 * @since 2024-05-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/maintain/by/score/question")
@Api(value = "保养评分工作项评分问题", tags = "保养评分工作项评分问题接口")
public class MaintainByScoreQuestionController extends BladeController {

	private final IMaintainByScoreQuestionService maintainByScoreQuestionService;
	private final IMaintainPlanContentService planContentService;
	private final ByScoreQuestionAppealService appealService;

	/**
	 * 分页 保养评分工作项评分问题
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "问题列表", notes = "传入maintainByScoreQuestion")
	public R<List<MaintainByScoreQuestion>> list(Long planId, String ids) {
		List<MaintainByScoreQuestion> list;
		if (StrUtil.isNotEmpty(ids)) {
			List<String> idss = Arrays.asList(ids.split(","));
			list = maintainByScoreQuestionService.listByIds(idss);
		} else {
			list = maintainByScoreQuestionService.list(Wrappers.<MaintainByScoreQuestion>lambdaQuery().eq(MaintainByScoreQuestion::getPlanId, planId).orderByAsc(MaintainByScoreQuestion::getCreateTime));
		}
		return R.data(list);
	}


	/**
	 * 新增或修改 保养评分工作项评分问题
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入maintainByScoreQuestion")
	public R submit(@Valid @RequestBody MaintainByScoreQuestion maintainByScoreQuestion) {
		return R.status(maintainByScoreQuestionService.addAndUpdate(maintainByScoreQuestion));
	}


	/**
	 * 删除 保养评分工作项评分问题
	 */
	@GetMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam Long checkHistoryId) {
		MaintainByScoreQuestion byScoreQuestion = maintainByScoreQuestionService.getOne(Wrappers.<MaintainByScoreQuestion>lambdaQuery().eq(MaintainByScoreQuestion::getCheckHistoryId, checkHistoryId));
		if (byScoreQuestion != null && byScoreQuestion.getChildPlanId() == null) {
			maintainByScoreQuestionService.removeById(byScoreQuestion.getId());
		}
		return R.status(true);
	}


	/**
	 * 分页 保养评分工作项评分问题
	 */
	@GetMapping("/verify/update")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "校验工单是否可以修改", notes = "传入工单id")
	public R<Boolean> verifyUpdate(Long planId, Long checkHistoryId) {
		if (checkHistoryId != null) {
			MaintainByScoreQuestion serviceOne = maintainByScoreQuestionService.getOne(Wrappers.<MaintainByScoreQuestion>lambdaQuery().eq(MaintainByScoreQuestion::getCheckHistoryId, checkHistoryId));
			if (serviceOne == null) {
				return R.data(true);
			} else {
				return R.data(serviceOne.getChildPlanId() != null ? false : true);
			}
		}
		List<MaintainByScoreQuestion> list = maintainByScoreQuestionService.list(Wrappers.<MaintainByScoreQuestion>lambdaQuery().eq(MaintainByScoreQuestion::getPlanId, planId).orderByDesc(MaintainByScoreQuestion::getCreateTime));
		List<MaintainByScoreQuestion> collect = list.stream().filter(o -> o.getChildPlanId() != null).collect(Collectors.toList());
		return R.data(collect.size() > 0 ? false : true);
	}


	@GetMapping("/getProblemStatus")
	@ApiOperationSupport(order = 33)
	@ApiOperation(value = "问题点状态统计")
	public R<ProblemStatusVo> getProblemStatus() {
		return R.data(maintainByScoreQuestionService.getProblemStatus());
	}


	@PostMapping("/getProblemResultList")
	@ApiOperationSupport(order = 33)
	@ApiOperation(value = "问题点分页列表")
	public R<IPage<ByProblemResultVo>> getProblemResultList(@RequestBody ByProblemSearchDTO byProblemSearchDTO) {
		return R.data(maintainByScoreQuestionService.getProblemResultList(byProblemSearchDTO));
	}


	@PostMapping("/down/excel")
	@ApiOperationSupport(order = 33)
	@ApiOperation(value = "问题点分页列表")
	public void downExcel(HttpServletResponse response, @RequestBody ByProblemSearchDTO byProblemSearchDTO) throws IOException {
		List<ByProblemResultVo> byProblemResultVos = maintainByScoreQuestionService.downExcel(byProblemSearchDTO);

		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title = CollUtil.newArrayList("项目名称", "电梯位置", "任务编号", "实际执行人", "完成时间", "工单申诉", "申诉状态", "申诉结果", "作业合规结果", "位置", "工作项名称", "问题类型", "问题描述", "问题申诉", "创建人", "问题处理状态", "调度人", "整改工单", "整改结果", "创建时间");
			rows.add(title);
			for (ByProblemResultVo byProblemResultVo : byProblemResultVos) {
				List<String> row = new ArrayList<>();
				row.add(byProblemResultVo.getBuildingName());
				row.add(byProblemResultVo.getElevatorAddress());
				row.add(byProblemResultVo.getPlanId().toString());
				row.add(Convert.toStr(byProblemResultVo.getUserNames()));
				if (byProblemResultVo.getPlanEndTime() != null) {
					row.add(Convert.toStr(DateUtil.format(byProblemResultVo.getPlanEndTime(), "yyyy-MM-dd HH:mm:ss")));
				} else {
					row.add("/");
				}
				if (byProblemResultVo.getAppealType() == null) {
					row.add("/");
				} else if (Convert.toInt(byProblemResultVo.getAppealType(), 1) == 1) {
					row.add("可申诉");
				} else {
					row.add("不可申诉");
				}
				if (Convert.toInt(byProblemResultVo.getAppealStatus(), -1) == 1) {
					row.add("待申诉");
				} else if (Convert.toInt(byProblemResultVo.getAppealStatus(), -1) == 2) {
					row.add("已申诉");
				} else {
					row.add("/");
				}
				if (Convert.toInt(byProblemResultVo.getAppealResult(), -1) == 1) {
					row.add("待审核");
				} else if (Convert.toInt(byProblemResultVo.getAppealResult(), -1) == 2) {
					row.add("审核通过");
				} else if (Convert.toInt(byProblemResultVo.getAppealResult(), -1) == 3) {
					row.add("审核不通过");
				} else {
					row.add("/");
				}
				row.add(Convert.toInt(byProblemResultVo.getIsPass(), 1) == 1 ? "合规" : "不合规");
				row.add(Convert.toStr(byProblemResultVo.getLocationTypeName()));
				row.add(Convert.toStr(byProblemResultVo.getName()));
				if (byProblemResultVo.getIssueType() != null) {
					//问题类型1:合规问题2:质量问题3:清洁问题4:其它
					if (byProblemResultVo.getIssueType() == 1) {
						row.add(Convert.toStr("合规问题"));
					} else if (byProblemResultVo.getIssueType() == 2) {
						row.add(Convert.toStr("质量问题"));
					} else if (byProblemResultVo.getIssueType() == 3) {
						row.add(Convert.toStr("清洁问题"));
					} else if (byProblemResultVo.getIssueType() == 4) {
						row.add(Convert.toStr("其它") + Convert.toStr(byProblemResultVo.getOtherDesc(), ""));
					} else {
						row.add("/");
					}
				} else {
					row.add("/");
				}
				row.add(Convert.toStr(byProblemResultVo.getQuestionDesc()));
				row.add(Convert.toInt(byProblemResultVo.getScoreIssueStatus(), -1) == 1 ? "不可申诉" : "可申诉");
				row.add(Convert.toStr(byProblemResultVo.getCreateUserName()));
				row.add(Convert.toStr(byProblemResultVo.getChildPlanId() == null ? "未处理" : "已处理"));
				row.add(Convert.toStr(byProblemResultVo.getChildPlanCreateUserName()));
				row.add(Convert.toStr(byProblemResultVo.getChildPlanId() == null ? "0" : String.format("%s(1)", MaintainPlanContentEnum.getName(byProblemResultVo.getChildPlanType()))));
				if (byProblemResultVo.getChildPlanId() != null) {
					if (byProblemResultVo.getPlanStatus() == 2) {
						row.add("待整改");
					} else if (byProblemResultVo.getPlanStatus() == 3) {
						row.add("整改中");
					} else if (byProblemResultVo.getPlanStatus() == 4) {
						row.add("整改完成");
					} else {
						row.add("已关闭");
					}
				} else {
					row.add("/");
				}
				row.add(DateUtil.format(byProblemResultVo.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
				rows.add(row);
			}
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (
			Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}

	}


	/**
	 * 功能描述: 发送响应流方法
	 */
	private void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
